iT邦幫忙

2025 iThome 鐵人賽

DAY 7
0
Software Development

30天收斂後端開發心法系列 第 7

30天收斂後端開發心法 - (7) php artisan command

  • 分享至 

  • xImage
  •  

前言

在 Laravel 專案中,除了使用者操作可以觸發邏輯(例如發送 HTTP Request),我們也可以讓系統自動執行程式碼。
Laravel 提供了 Artisan Command 機制,讓我們可以撰寫自定義的命令來做資料處理、寄信、同步資料等工作,尤其適合搭配排程執行。

建立一個 Laravel Command

使用 Artisan 指令產生:
php artisan make:command SendEmails

生成後的檔案位置為:
app/Console/Commands/SendEmails.php

範例 Command:SendEmails

以下是示範範本:

namespace App\Console\Commands;
use App\Models\User; // ✅ 修正命名空間
use App\Services\DripEmailer; // ✅ 假設這是你的寄信 service
use Illuminate\Console\Command;
class SendEmails extends Command
{
    /**
     * Artisan 指令名稱與參數定義
     */
    protected $signature = 'email:send {user} {--date=}';
    /**
     * 說明此指令的用途
     */
    protected $description = 'Send drip emails to a specific user';
    /**
     * Email service 注入
     */
    protected DripEmailer $drip;
    public function __construct(DripEmailer $drip)
    {
        parent::__construct();
        $this->drip = $drip;
    }
    /**
     * 執行指令
     */
    public function handle()
    {
        $email = $this->argument('user');
        $date = $this->option('date') ?? now()->toDateString();
        $user = User::where('email', $email)->first();
        if (! $user) {
            $this->error("User not found: $email");
            return;
        }
        $this->info("Sending email to {$user->email} for date {$date}");
        $this->drip->send($user, $date);
    }
}

執行指令

透過 CLI 執行:
php artisan email:send test@mail.com --date=2025-01-01

加入排程 Schedule

若要定期執行這支指令,可在 app/Console/Kernel.php 中設定:

use Illuminate\Console\Scheduling\Schedule;

protected function schedule(Schedule $schedule): void
{
    // 記得這裡不能帶參數變數,要直接寫好
    $schedule->command('email:send test@mail.com --date=' . now()->toDateString())->daily();
}

上一篇
30天收斂後端開發心法 - (6) 淺談測試
下一篇
30天收斂後端開發心法 - (8) Laravel 驗證
系列文
30天收斂後端開發心法30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言